package com.bilibili.api.aspect;

import com.bilibili.api.support.UserSupport;
import com.bilibili.domain.constant.AuthRoleConstant;
import com.bilibili.domain.entity.AuthRole;
import com.bilibili.domain.entity.UserMoments;
import com.bilibili.domain.entity.UserRole;
import com.bilibili.domain.exception.ConditionException;
import com.bilibili.service.AuthRoleService;
import com.bilibili.service.UserRoleService;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * projectName:com.bilibili.api.aspect
 *
 * @author 飞
 * @create by 2024/6/1117:04
 * description:
 */
@Aspect
@Order(1)
@Component
public class DataLimitedRoleAspect {

    @Resource
    private UserSupport userSupport;

    @Resource
    private UserRoleService userRoleService;

    @Resource
    private AuthRoleService authRoleService;

    @Pointcut("@annotation(com.bilibili.domain.annotation.DataLimited)")
    public void check() {

    }

    @Before("check()")
    public void doBefore(JoinPoint joinPoint) {
        // 获取当前用户ID
        Long userId = userSupport.getCurrentUserId();
        // 根据用户ID获取用户角色列表
        List<UserRole> userRoleList = userRoleService.getByUserId(userId);

        for (UserRole userRole : userRoleList) {
            AuthRole authRole = authRoleService.getById(userRole.getRoleId());
            userRole.setRoleName(authRole.getName());
            userRole.setRoleCode(authRole.getCode());
        }
        // 获取当前用户拥有的角色代码集合
        Set<String> roleCodeSet = userRoleList.stream().map(UserRole::getRoleCode).collect(Collectors.toSet());
        Object[] args = joinPoint.getArgs();
        for (Object arg : args) {
            if (arg instanceof UserMoments) {
                UserMoments userMoments = (UserMoments) arg;
                String type = userMoments.getType();
                if (roleCodeSet.contains(AuthRoleConstant.ROLE_LV1) && !"0".equals(type)) {
                    throw new ConditionException("参数异常！");
                }
            }
        }
    }
}
